<?php


namespace app\api\controller;

use app\api\traits\CommonTrait;
use app\api\validate\BaseValiate;
use app\BaseController;
use think\App;
use think\Exception;

/**
 * Class Base
 * @package app\api\controller
 * @desc 基类,通用功能供其它类继承使用
 */
class Base extends BaseController
{
    use CommonTrait;

    protected $logId;// 日志id

    // 初始化
    protected function initialize()
    {
        parent::initialize();
        $this->addLog();// 记录请求日志
        $ret = $this->checkParams($this->request->param());// 验证参数
//        halt($ret);
        if ($ret) {
            return $this->returnResult(400, $ret);
        }
    }
    // 初始化方法
//    public function __construct(App $app)
//    {
//        parent::__construct($app);
//        $this->addRequestLog();
//        // 验证参数
//        $checkRet = $this->checkParams($this->request->param());
//        if ($checkRet) {
//            $ret = [
//                'code' => 400,
//                'msg'  => $checkRet,
//            ];
//            $this->returnResult($ret['code'], $ret['msg']);
//            header('Content-Type:text/json;charset=utf-8');
//            echo json_encode($ret, JSON_UNESCAPED_UNICODE);
//            die;
//        }
//    }

    // 记录请求日志
    public function addLog()
    {
        $url   = $this->request->url();
        $param = $this->request->param();
        if (empty($this->logId)) {
            $this->logId = date('YmdHis');
        }
        self::addRequestLog($this->logId, $url, $param);
    }

    // 统一下发数据
    public function returnResult($code, $msg = '', $data = [])
    {
        $ret = self::returnArr($code, $msg, $data);
        $msg = sprintf('日志id:%s,下发数据:%s', $this->logId,
            json_encode($ret, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
        self::writeLog($msg);
        return self::returnJson($code, $ret['msg'], $ret['data']);
    }

    /**
     * 验证数据
     */
    protected function checkParams($data)
    {
        try {
            // 判断方法是否定义,定义了才进行验证
            $method     = $this->request->action();
            $ruleArr    = BaseValiate::$ruleArr;
            $methodRule = isset($ruleArr[$method]) ? $ruleArr[$method] : [];
            if (empty($methodRule)) {
                return 0;
            }
            $v       = new \think\Validate();
            $message = isset(BaseValiate::$messageArr[$method]) ? BaseValiate::$messageArr[$method] : [];
            $v->rule($methodRule)->message($message)->batch(true)->check($data);
            $error    = $v->getError();
            $errorArr = current($error);
            if (empty($errorArr)) {
                return 0;
            }
            return $errorArr;
        } catch (Exception $e) {
            return '参数验证异常-' . $e->getMessage();
        }
    }
}